from flask import Flask, request, jsonify, Response
import queue
import threading
import time
from collections import defaultdict

app = Flask(__name__)

# 存储串口数据的字典，使用ID区分不同设备
data_dict = defaultdict(list)

# 存储视频帧的字典，使用ID区分不同设备
video_dict = defaultdict(queue.Queue)
lock = threading.Lock()

@app.route('/upload_video/<int:device_id>', methods=['POST'])
def upload_video(device_id):
    if 'video' not in request.files:
        return jsonify({"error": "No video part"}), 400

    video_file = request.files['video']

    if video_file.filename == '':
        return jsonify({"error": "No selected video"}), 400

    # 将视频帧数据添加到对应设备ID的队列中
    with lock:
        video_dict[device_id].put(video_file.read())

    return jsonify({"message": "Video uploaded successfully"}), 200

@app.route('/upload_data/<int:device_id>', methods=['POST'])
def upload_data(device_id):
    serial_data = request.form.get('serial_data')
    time_localtime = time.localtime(time.time())
    time_str = time.strftime("%Y-%m-%d %H:%M:%S", time_localtime)
    if not serial_data:
        return jsonify({time_str: "No serial data"}), 400

    # 将串口数据添加到对应设备ID的列表中
    data_dict[device_id].append([time_str, serial_data])

    return jsonify({"message": "Data uploaded successfully"}), 200

def generate_video_stream(device_id):
    while True:
        with lock:
            if not video_dict[device_id].empty():
                frame = video_dict[device_id].get()
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
            else:
                pass
        time.sleep(0.01)

@app.route('/get_video/<int:device_id>', methods=['GET'])
def get_video(device_id):
    return Response(generate_video_stream(device_id), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/get_data/<int:device_id>', methods=['GET'])
def get_data(device_id):
    if not data_dict[device_id]:
        return jsonify("No data available"), 404

    # 获取队列中的全部串口数据
    data = data_dict[device_id]

    return jsonify(data), 200

@app.route('/get_data_rst/<int:device_id>', methods=['GET'])
def get_data_rst(device_id):
    if not data_dict[device_id]:
        return jsonify("No data available"), 404

    # 获取队列中的全部串口数据并重置队列
    data = data_dict[device_id]
    data_dict[device_id] = []

    return jsonify(data), 200

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5800)
